import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/string_extension.dart';
import 'package:yt_devops/pages/mine/user_manage/mine_add_user/models/organization_model.dart';
import 'package:yt_devops/pages/mine/user_manage/user_manage_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

import 'models/node.dart';

class MineAddUserController extends GetxController {
  final _authServices = Get.put(AuthServices());
  bool enableCommit = false;
  String avatar = '';
  final TextEditingController roleController = TextEditingController();
  final TextEditingController organizationController = TextEditingController();
  final TextEditingController userNameController = TextEditingController();
  final TextEditingController accountNameController = TextEditingController();
  final TextEditingController mobileController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController relationSiteController = TextEditingController();
  final TextEditingController statusController = TextEditingController();
  TextEditingController pwdController = TextEditingController();
  TextEditingController againPwdController = TextEditingController();
  final TextEditingController remarkController = TextEditingController();
  List pushTypeList = [0,1];//推送方法数组
  List pushLevelList = ['error','alarm',  'warn', 'info'];
  UserManageController controller = Get.find();
  List<String> conditions = [
    ResKey.installManu.tr,
    ResKey.mineUserManagerUserOwner.tr,
  ];
  List<String> roleId = ['3', '4'];
  int selectedRoleIndex = -1;
  String selectedRoleId = '';
  List<OrganizationModel> organizationList = [];
  List<String> organizationShowList = [];
  int selectedOrganizationIndex = 0;
  String organizationId = '';
  // String organizationName = '';
  List chooseSiteList = [];
  int roleTypeId = RoleType.owner.value;
  List<dynamic> existOrgList = [];
  int selectedRoleTemp = -1; //选择临时的角色index,因为确定按钮里面没有索引
  bool isShowOrganizationRight = true; //是否可以点击选择组织
  int type = 0;
  List<String> roleShowList = [];
  List<dynamic> rolesList = [];
  int selectedStatusIndex = 0;
  List<String> statusList = [
    ResKey.mineUserManagerUserValid.tr,
    ResKey.mineUserManagerUserInvalid.tr
  ];
  List<String> systemBuiltRoles = [
    '1',//超级管理员
    '3',//安装商
    '5',//运营商
    '7',//访客
    '29'//系統管理员
  ]; //系统内置角色都不能关联站点(除了业主)
  List selectedSitesIds = [];
  List selectedSitesNames = [];
  @override
  void onInit() {
    super.onInit();
    var args = Get.arguments;
    if (args != null) {
      if (args['type'] != null) {
        type = args['type'];
        Log.d('type===' + type.toString());
      }
    }
    if (type == 3) {
      ///业主
      roleController.text = ResKey.mineUserManagerUserOwner.tr;
      selectedRoleId = '4';
    }
  }

  @override
  void onReady() {
    //如果不是业主,需要去请求角色有哪些,如果没有角色弹窗就不显示对应的角色选项
    if (UserEntityManager().userModel.roles != null &&
        (UserEntityManager().userModel.roles?[0].roleId! != 4)) {
      // _getExistOrganization();
    }
  }

  @override
  void onClose() {}

  ///选择关联站点
  chooseRelateSite() {
    Log.d('chooseRelateSite==');
    if(type == 0){
      if (selectedRoleId.isEmpty) {
        showError(ResKey.mineUserManagerUserChooseRole.tr);
      } else {
        Get.toNamed(RouterPath.adminChooseRelateSite, arguments: {
          'roleId': selectedRoleId,
          'selectedSitesIds':selectedSitesIds,
          'selectedSitesNames':selectedSitesNames
        })?.then((result){
          Log.d('result==' + result.toString());
          if(result != null){
            if(result['selectedSitesNames'] != null) {
              selectedSitesNames = result['selectedSitesNames'];
              if (selectedSitesNames.length > 1) {
                relationSiteController.text = selectedSitesNames.first + '...';
              } else {
                relationSiteController.text = selectedSitesNames.first;
              }
            }
            if (result['selectedSitesIds'] != null) {
              selectedSitesIds = result['selectedSitesIds'];
              chooseSiteList.clear();
              for (var element in selectedSitesIds) {
               List ids = element.toString().split('+');
               if(ids.isNotEmpty){
                 chooseSiteList.add(ids.last.toString());
               }
              }
              Log.d('selectedSitesIds===' + selectedSitesIds.toString());
            }

            if(result['returnList'] != null && result['returnList'].isNotEmpty && selectedSitesIds.isNotEmpty){
              List siteList = result['returnList'];
              chooseSiteList.clear();
              for (var element in siteList) {
                if(selectedSitesIds.contains(element['id'].toString())){
                  List<String> siteIds = collectSiteIds(element, element['id'].toString());
                  chooseSiteList.addAll(siteIds);
                }
              }
                chooseSiteList.removeWhere((id) => id.startsWith("#"));
              Log.d('chooseSiteList===' + chooseSiteList.toString());
            }
            update();
          }

        });
      }
    }else{
      if (organizationId.isEmpty) {
        showError(ResKey.mineUserManagerChooseOrganizationFirst.tr);
      } else {
        Get.toNamed(RouterPath.mineUserManagerChooseSite, arguments: {
          'orgId': int.parse(organizationId),
          'chooseSite': chooseSiteList,
          'isAddUser': true
        });
      }
    }
    checkCanCommit();
  }
  ///检查是否可以提交
  void checkCanCommit() {
    if (statusController.text.isNotEmpty &&
        userNameController.text.isNotEmpty &&
        accountNameController.text.isNotEmpty &&
        roleController.text.isNotEmpty &&
        organizationController.text.isNotEmpty &&
        pwdController.text.isNotEmpty &&
        againPwdController.text.isNotEmpty&& pushTypeList.isNotEmpty && pushLevelList.isNotEmpty) {
      if(systemBuiltRoles.contains(selectedRoleId)){
        enableCommit = true;
      }else {
        if(!systemBuiltRoles.contains(selectedRoleId) && relationSiteController.text.isNotEmpty){
          Log.d('checkCanCommit===' + enableCommit.toString());
          enableCommit = true;
        }else{
          Log.d('checkCanCommit===' + enableCommit.toString());
          enableCommit = false;
        }
      }

    } else {
      enableCommit = false;
    }
    Log.d('checkCanCommit===' + selectedRoleId.toString());
    Log.d('checkCanCommit===' + systemBuiltRoles.contains(selectedRoleId).toString());
    Log.d('checkCanCommit===' + enableCommit.toString());
    update();
  }

  ///保存数据
  Future<void> save() async {
    if (emailController.text.isNotEmpty && !emailController.text.tyIsEmail) {
      EasyLoading.showError(ResKey.pleEnterCorrectEmail.tr);
      return;
    }
    if (pwdController.text != againPwdController.text) {
      EasyLoading.showError(ResKey.mineUserManagerPwdInconsistency.tr);
      return;
    }
    if (!pwdController.text.tyIsPassword) {
      EasyLoading.showError(ResKey.mineUserManagerPwdLimit.tr);
      return;
    }
    var param = {
      "userName": accountNameController.text,
      "nickName": userNameController.text,
      "avatar": avatar,
      "phone": mobileController.text,
      "orgId": organizationId,
      "roleIds": [selectedRoleId],
      "status": selectedStatusIndex,
      'email': emailController.text,
      'siteIds': chooseSiteList,
      'webConfig':chooseSiteList,
      "password": pwdController.text,
      "confirmPassword": againPwdController.text,
      'alarmPushModes': pushTypeList,
      'alarmPushLevels': pushLevelList,
      'remark': remarkController.text??''
    };
    Log.d('param===' + param.toString());
    // return;
    showLoading(toast: ResKey.loading.tr);
    var result =
        await _authServices.userManagerAddUser(param, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      FuncUtils.requestTipsDislog(
          Get.context, ResKey.mineUserManagerSaveSuccess.tr, true,
          duration: const Duration(milliseconds: 1000));
      controller.addUserRefreshList();
      Future.delayed(const Duration(milliseconds: 1000), () {
        // 延迟执行的代码
        Get.back();
      });
    }
  }

  ///关联站点后的回调
  chooseSiteListCallBack(List list) {
    if (list.isNotEmpty) {
      if (list.length == 1) {
        relationSiteController.text = list.first['name'];
      } else {
        relationSiteController.text = list.first['name'] + '...';
      }
      chooseSiteList.clear();
      for (var element in list) {
        chooseSiteList.add(element['id']);
      }
    }
    checkCanCommit();
    update();
  }

  ///如果是产品管理员或者admin这类角色需要去调用接口拿到所有可以展示的角色
  chooseRole() async {
    showLoading(toast: ResKey.loading.tr);
    var params = {'builtInRole': type == 0 ? 0 : 1, 'manageOrgType': type};
    var result = await _authServices.getRoleList(params, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();

    if (result != null) {
      List<dynamic> list = result;
      if (list.isNotEmpty) {
        Log.d('list===' + list.toString());
        rolesList.clear();
        roleShowList.clear();
        for (int i = 0; i < list.length; i++) {
          var element = list[i];
          roleShowList.add(element['roleName']);
          rolesList.add(element);
          if (element['roleId'].toString() == selectedRoleId) {
            selectedRoleIndex = i;
          }
        }
        showBottomPop(roleShowList, ResKey.mineUserManagerUserChooseRole.tr, isOrganization: false);
      }
    }
  }

  ///选择组织
  chooseOrganization() async {
    ///产品管理员和自定义角色type都传0 ,1安装商  3业主(终端用户)/运营商
    if (selectedRoleId.isEmpty) {
      showError(ResKey.pleSelectARole.tr);
      return;
    }
    // if(selectedRoleId == '3' || selectedRoleId == '4'){//如果是安装商或者业主则底部弹出选择 不需要组织树,else跳转其他页面需要组织树
    showLoading(toast: ResKey.loading.tr);
    String type = '0';
    if (selectedRoleId == '3') {
      ///安装商角色
      type = '1';
    } else if (selectedRoleId == '4'|| selectedRoleId == '36')  {
      ///业主
      type = '3';
    }
    List result = await _authServices.productOrganizationList({'type': type},
        onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result.isNotEmpty) {
      organizationShowList.clear();
      organizationList.clear();
      for (int i = 0; i < result.length; i++) {
        var element = result[i];
        organizationList.add(OrganizationModel.fromJson(element));
        organizationShowList.add(element['orgName']);
        if (organizationId == element['orgId'].toString()) {
          selectedOrganizationIndex = i;
        }
      }

      showBottomPop(
        organizationShowList,
        ResKey.selectOrganization.tr,
      );
    }

  }

  ///弹出底部弹窗
  showBottomPop(List<String> list, String title, {bool isOrganization = true}) {
    BrnMultiDataPicker(
      context: Get.context!,
      title: title,
      confirmClick: (indexList) {
        if (isOrganization) {
          selectedOrganizationIndex = indexList[0];
          OrganizationModel model = organizationList[selectedOrganizationIndex];
          organizationController.text = model.orgName ?? '';
          organizationId = model.orgId != null ? model.orgId.toString() : '0';
          relationSiteController.text = '';
          chooseSiteList = [];
          selectedSitesIds = [];
        } else {
          if (selectedRoleIndex == indexList[0]) {
            ///选择的角色和当前角色一样则不进行任何操作
            return;
          }
          selectedRoleIndex = indexList[0];
          organizationController.text = '';
          organizationId = '';
          selectedRoleId = rolesList[selectedRoleIndex]['roleId'].toString();
          roleController.text = roleShowList[selectedRoleIndex];
          relationSiteController.text = '';
          chooseSiteList = [];
          selectedSitesIds = [];
        }
        Log.d('selectedRoleId===' + selectedRoleId.toString());
        checkCanCommit();
        update();
      },
      delegate: Brn1RowDelegate(list,
          firstSelectedIndex:
              isOrganization ? selectedOrganizationIndex : selectedRoleIndex),
    ).show();
  }

  ///获取拿到的id重新请求数据
  void getOrganizationId(String id, String name) {
    organizationId = id;
    organizationController.text = name;
    update();
  }

  ///组织是否可以选中
  void organizationCanEdit() {
    if (UserEntityManager().userModel.roles != null &&
        UserEntityManager().userModel.roles?[0].roleId! == 4) {
      //业主无法更改组织
      isShowOrganizationRight = false;
    } else if ((UserEntityManager().userModel.roles != null &&
            UserEntityManager().userModel.roles?[0].roleId! == 3) &&
        selectedRoleId == '3') {
      //如果是安装商,选择的角色也是安装商,则无法更改
      isShowOrganizationRight = false;
    } else if ((UserEntityManager().userModel.roles != null &&
        UserEntityManager().userModel.roles?[0].roleId! == 4)) {
      //业主组织无法选择
      isShowOrganizationRight = false;
    } else if (UserEntityManager().userModel.roles != null &&
        UserEntityManager().userModel.roles?[0].roleId! == 3 &&
        roleId.length == 1) {
      //当前登录用户为安装商,但是业主无组织
      isShowOrganizationRight = false;
      roleController.text = ResKey.installManu.tr;
      selectedRoleIndex = 0;
      selectedRoleId = '3';
    } else {
      isShowOrganizationRight = true;
    }

  }
// 递归遍历方法
  List<String> collectSiteIds(dynamic node, String targetId) {
    // 如果找到目标ID
    if (node['id'] == targetId) {
      // 获取当前节点ID
      List<String> ids = [node['id']];
      // 确保 children 存在且非空
      if (node['children'] != null && node['children'].isNotEmpty) {
        // 递归遍历所有子节点并收集它们的ID
        ids.addAll(node['children']
            .expand<String>((child) => collectSiteIds(child, child['id']))
            .toList());
      }
      return ids;
    }
    // 如果当前节点不是目标ID，则继续递归查找子节点
    if (node['children'] != null && node['children'].isNotEmpty) {
      for (var child in node['children']) {
        List<String> result = collectSiteIds(child, targetId);
        if (result.isNotEmpty) {
          return result;
        }
      }
    }
    // 如果没有匹配的ID，则返回空列表
    return [];
  }
}
